package com.adminsystem.common.security;

import com.adminsystem.common.exception.UserAccountLockException;
import com.adminsystem.entity.SysUser;
import com.adminsystem.entity.SysUserRole;
import com.adminsystem.service.SysUserRoleService;
import com.adminsystem.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.getByUserName(username);
        List<SysUserRole> sysUserRoleList=sysUserRoleService.list(new QueryWrapper<SysUserRole>().inSql("user_id","SELECT id FROM sys_user WHERE username='"+username+"'"));
        System.out.println("sysUser:" + sysUser);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        } else if ("1".equals(sysUser.getStatus())) {
            throw new UserAccountLockException("该用户账号被封禁，具体请联系管理员");
        }
        else if (sysUserRoleList.size()==0) {
            throw new UserAccountLockException("该用户账号没权限，具体请联系管理员");
        }
        sysUser.setLastLoginDate(new Date());
        userService.updateById(sysUser);
        return new User(sysUser.getUsername(), sysUser.getPassword(), getUserAuthority(sysUser.getId()));
    }

    public List<GrantedAuthority> getUserAuthority(long userId) {
        String authorityStr = userService.getUserAuthorityInfo(userId);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authorityStr);
    }
}
